/*
	Anonymous Image Board Image Downloader - program for downloading pictures from AIB
	Copyright (C) 2011-2012 Metallhead <Metallhead@megabox.ru>

	HomePage:    http://code.google.com/p/aibid/

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QTranslator>
#include <QLocale>
#include <QSettings>
#include <QDir>
#include <QTextCodec>
#include <QFile>
#include <QDateTime>
#include <QTime>
#include <QtDebug>
#include "common.h"

void checkDir(QString absoluteDirPosition)
{
	QDir dir(QDir::toNativeSeparators(absoluteDirPosition));
	if(!dir.exists())
		dir.mkpath(".");
}

void checkDirs()
{
	QString appFilesLocation = Common::filePlace("");
	checkDir(appFilesLocation);
	checkDir(appFilesLocation + "/logs");
	checkDir(appFilesLocation + "/translations");
}

bool checkFile(QDir destinationDir, QDir searchDir, QString fileName)
{
	QStringList files = destinationDir.entryList(QDir::Files);
	if(!files.contains(fileName))
	{
		QFile file(searchDir.absoluteFilePath(fileName));
		if(file.exists())
		{
			file.copy(destinationDir.absoluteFilePath(fileName));
			return true;
		}
		else
			return false;
	}
	else
	{
		uint currFile = Common::getHash(destinationDir.absoluteFilePath(fileName));
		if(!QFile::exists(searchDir.absoluteFilePath(fileName)))
			return true;
		uint reserveFile = Common::getHash(searchDir.absoluteFilePath(fileName));
		if(currFile!=reserveFile)
		{
			QFile::remove(destinationDir.absoluteFilePath(fileName));
			QFile::copy(searchDir.absoluteFilePath(fileName),destinationDir.absoluteFilePath(fileName));
		}
		return true;
	}
}

void checkFiles()
{
	QDir searchDir;
#ifdef Q_OS_LINUX
	searchDir.setPath("/etc/AIBID/");
#endif
#ifdef Q_OS_WIN
	searchDir.setPath(".");
#endif
#ifdef Q_OS_MAC
	searchDir.setPath(QApplication::applicationDirPath());
#endif
	QDir dir(Common::filePlace(""));
	checkFile(dir, searchDir, "parsers.xml");
#ifdef Q_OS_WIN
	checkFile(dir, searchDir, "files.lst");
#endif
#ifdef Q_OS_MAC
	checkFile(dir, searchDir, "mac.ver");
#endif
	dir.cd("translations");
	searchDir.cd("translations");
	checkFile(dir, searchDir, "aibid_ru.qm");
	checkFile(dir, searchDir, "aibid_en.qm");
}

void messageOutput(QtMsgType type, const char *msg)
{
	QString fileName = Common::filePlace("logs/"+QString::number(QDate::currentDate().day()) + "." + QString::number(QDate::currentDate().month()) + "." + QString::number(QDate::currentDate().year()));
	QFile file(fileName);
	if(!file.exists())
		file.open(QIODevice::WriteOnly);
	else
		file.open(QIODevice::WriteOnly|QIODevice::Append);
	QString time = QString::number(QTime::currentTime().hour()) + ":" + QString::number(QTime::currentTime().minute()) + ":" + QString::number(QTime::currentTime().second());
	switch (type)
	{
	case QtDebugMsg:
		file.write(QString(time + " Debug: " + QString(msg) + "\r\n").toStdString().c_str());
		break;
	case QtWarningMsg:
		file.write(QString(time + " Warning: " + QString(msg) + "\r\n").toStdString().c_str());
		break;
	case QtCriticalMsg:
		file.write(QString(time + " Critical: " + QString(msg) + "\r\n").toStdString().c_str());
		break;
	case QtFatalMsg:
		file.write(QString(time + " Fatal: " + QString(msg) + "\r\n").toStdString().c_str());
		break;
	}
	file.close();
}

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	a.setOrganizationName("Anonymous");
	a.setApplicationName("AIBID");

	checkDirs();
	checkFiles();

	qInstallMsgHandler(messageOutput);

	qDebug() << "Program started";

	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
	qDebug() << "trying to load settings";
	QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());

	if(QString(settings.value("settings/currentLanguage").toString())==QString(""))
		settings.setValue("settings/currentLanguage",QVariant("en"));
	if(QString(settings.value("settings/path").toString())==QString(""))
		settings.setValue("settings/path",QVariant(QDir::homePath()));
	if(QString(settings.value("settings/time").toString())==QString(""))
		settings.setValue("settings/time",QVariant("10"));
	if(!settings.value("settings/hashCheck").toBool())
		settings.setValue("settings/hashCheck",false);
	if(!settings.value("settings/tray").toBool())
		settings.setValue("settings/tray",false);
	if(!settings.value("settings/manualUpdate").toBool())
		settings.setValue("settings/manualUpdate",false);
	if(!settings.value("settings/rememberThreads").toBool())
		settings.setValue("settings/rememberThreads",false);
	if(!settings.value("settings/close").toBool())
		settings.setValue("settings/close",false);
	if(settings.value("settings/threadsLimit").toString()==QString(""))
		settings.setValue("settings/threadsLimit",QVariant("10"));
	if(settings.value("settings/dbUpdateInterval").toString()==QString(""))
		settings.setValue("settings/dbUpdateInterval",10);
	if(settings.value("settings/windowState").toString()==QString(""))
		settings.setValue("settings/windowState",QVariant("normal"));
	if(settings.value("settings/width").toString()==QString(""))
		settings.setValue("settings/width",768);
	if(settings.value("settings/height").toString()==QString(""))
		settings.setValue("settings/height",256);


	qDebug() << "trying to load translations";
	QTranslator myTranslator;
	QString translationFile = Common::filePlace("translations/aibid_" + settings.value("settings/currentLanguage").toString() + ".qm");
	myTranslator.load(translationFile);
	a.installTranslator(&myTranslator);

	qDebug() << "trying to detect appName";
	QString appFullPath = a.applicationFilePath();
	QString appName = appFullPath.split("/").last();
	qDebug() << "AppName:" << appName;

#ifdef Q_OS_WIN
	a.addLibraryPath(QString("." + QString(QDir::separator()) + "plugins" + QString(QDir::separator())));
#endif

	MainWindow w(appName);
	w.show();
	return a.exec();
}
